
const app = getApp()
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
Page({
  data: {
    // userInfo: {
    //   avatarUrl: '/image/film/剧组人员（线）.png', // 头像图片地址
    //   name: '小明' // 姓名
    // },
    userInfo: null,
    img1: '/image/my/发布.png',
    img2: '/image/my/作品 (2).png',
    img3: '/image/my/求职.png',
    img4: '/image/my/收藏.png',
    img5: '/image/my/我的信息 (1).png',
    img6: '/image/my/我的简历.png',
    img7: '/image/my/实名认证.png',
    img8: '/image/my/设置.png',
    border: {
      color: '#f6f6f6',
    },
    avatarUrl:defaultAvatarUrl

  },
  goToMessage: function() {
    wx.navigateTo({
      url: '/pages/my-message/my-message'
    });
  },
  onLoad: function (options) {
    // 只有当全局数据中存在用户信息时才更新页面数据
    const userInfo = app.globalData.userInfo; // 注意这里的更改
    if (userInfo) {
        this.setData({
            userInfo: userInfo
        });
        app.globalData.user_openid = userInfo._openid;
    }
},

onShow: function () {
  // 页面显示时重新获取用户信息并更新页面数据
  this.loadData();
},
loadData: function () {
  wx.cloud.database().collection('user')
    .get()
    .then(res => {
      if (res.data.length) {
        const userInfo = res.data[0];
        // 更新全局用户信息
        app.globalData.userInfo = userInfo;
        app.globalData.user_openid = userInfo._openid;
        // 更新页面数据
        this.setData({
          userInfo: userInfo
        });
      } else {
        // 若未查询到用户信息，清空页面数据
        this.setData({
          userInfo: null
        });
      }
    })
    .catch(err => {
      console.error('查询用户信息失败：', err);
    });
},

  /**
     * 关闭/打开弹框
     */
    closeTank(e) {
      if (!this.data.userInfo_tank) {
          wx.cloud.database().collection('user')
              .get()
              .then(res => {
                  console.log("用户信息====", res);
                  if (res.data.length) {
                    const userInfo = res.data[0];
          
                    // 将用户信息存储到全局数据中
                    app.globalData.userInfo = userInfo;
                    app.globalData.user_openid = userInfo._openid;
                    console.log(app.globalData.user_openid)
          
                    this.setData({
                      userInfo: userInfo,
                      userInfo_tank: false,
                    });

                    wx.setStorageSync('user', userInfo);
                  } else {
                      console.log("还未注册====", res)
                      this.setData({
                          userInfo_tank: true
                      })
                  }
              }).catch(res => {
                  console.log('程序员提醒你请添加user表')
              })
      } else {
          this.setData({
              userInfo_tank: false
          })
      }

  },
  /**
   * 获取头像
   */
  onChooseAvatar(e) {
      console.log(e);
      this.setData({
          avatarUrl: e.detail.avatarUrl
      })
  },
  /**
   * 获取用户昵称
   */
  getNickName(e) {
      console.log(e);
      this.setData({
          nickName: e.detail.value
      })
  },

  /**
   * 提交
   */
  submit(e) {
      if (!this.data.avatarUrl) {
          return wx.showToast({
              title: '请选择头像',
              icon: 'error'
          })
      }
      if (!this.data.nickName) {
          return wx.showToast({
              title: '请输入昵称',
              icon: 'error'
          })
      }
      this.setData({
          userInfo_tank: false
      })
      wx.showLoading({
          title: '正在注册',
          mask: 'true'
      })
      let tempPath = this.data.avatarUrl

      let suffix = /\.[^\.]+$/.exec(tempPath)[0];
      console.log(suffix);

      //上传到云存储
      wx.cloud.uploadFile({
          cloudPath: 'user/avatar/' + new Date().getTime() + suffix, //在云端的文件名称
          filePath: tempPath, // 临时文件路径
          success: res => {
              console.log('上传成功', res)
              let fileID = res.fileID
              wx.hideLoading()
              wx.cloud.database().collection('user')
                  .add({
                      data: {
                          avatarUrl: fileID,
                          nickName: this.data.nickName,
                          authen:0,
                          cauthen:0,
                          identity:0,
                          login:true,
                          phone:'',
                          sex:'',
                          wechat:''




                      }
                  }).then(res => {
                      let user = {
                          avatarUrl: fileID,
                          nickName: this.data.nickName
                      }
                      //设置全局用户信息
                      app.globalData.userInfo = user
                      app.globalData.user_openid = userInfo._openid;
                      
    
                      // 注册成功
                      console.log('注册成功')
                      wx.setStorageSync('user', user);

                      //设置局部用户信息
                      this.setData({
                          userInfo: user,
                      })
                  }).catch(res => {
                      console.log('注册失败', res)
                      wx.showToast({
                          icon: 'error',
                          title: '注册失败',
                      })
                  })

          },
          fail: err => {
              wx.hideLoading()
              console.log('上传失败', res)
              wx.showToast({
                  icon: 'error',
                  title: '上传头像错误',
              })
          }
      })
  },

  logout(){
    console.log("退出登录");
    app.globalData.user_openid = '';
    app.globalData.userInfo = null
    wx.setStorageSync('user', null)
    this.setData({
        userInfo: null,
        login: false
    });

   
},
handleClick(e) {
  wx.navigateTo({
    url: '/pages/login/login' 
  });
},


})